//
//  PMCDepartmentViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/9.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class PMCDepartmentViewController: BaseViewController {
    
    private var viewModel: DepartmentViewModel? {
        didSet {
            collectionView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "新建咨询"
        setupCollectionView()
        setupRefresh()
    }
    
    private lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar()
        searchBar.barTintColor = .white
        searchBar.tintColor = .textDark
        searchBar.delegate = self
        searchBar.placeholder = "搜索科室"
        searchBar.setBackgroundImage(UIImage(color: .white), for: .any, barMetrics: .default)
        return searchBar
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = DepartmentViewFlowLayout()
        layout.delegate = self
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .background
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delaysContentTouches = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DepartmentViewCell.nibForCell(),
                                forCellWithReuseIdentifier: DepartmentViewCell.reuseIdentifier())
        return collectionView
    }()
    
    private lazy var resultSearchVc = DepartmentSearchResultController()
    
    private var isSearchBarEditing: Bool = false
}

extension PMCDepartmentViewController {
    private func setupCollectionView() {
        view.addSubview(searchBar)
        searchBar.snp.makeConstraints { (make) in
            make.top.equalTo(navBarH)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(searchBar.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    private func setupRefresh() {
        collectionView.mj_header = refreshHeader(action: #selector(loadData))
        collectionView.mj_header?.beginRefreshing()
    }
    
    private func endRefresh() {
        collectionView.mj_header?.endRefreshing()
    }
    
    @objc private func loadData() {
        DepartmentViewModel.getDepartmentList(success: { models in
            self.endRefresh()
            self.viewModel = DepartmentViewModel(models: models)
        }) { errorMsg in
            self.endRefresh()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc private func searchBarClicked() {
        resultSearchVc = DepartmentSearchResultController()
        let searchVc = SearchViewController(searchResultsController: resultSearchVc)
        searchVc.searchBar.becomeFirstResponder()
        searchVc.searchBar.delegate = self
        present(searchVc, animated: true)
    }
}

extension PMCDepartmentViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DepartmentViewCell.reuseIdentifier(),
                                                      for: indexPath) as! DepartmentViewCell
        if let vm = viewModel?.viewModel(for: indexPath) {
            cell.configure(with: vm)
        }
        return cell
    }
}

extension PMCDepartmentViewController: UICollectionViewDelegate, DepartmentViewFlowLayoutDelegate, UICollectionViewDelegateFlowLayout {
    func waterFlowLayout(layout: DepartmentViewFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        if let vm = viewModel?.viewModel(for: indexPath) {
            return vm.itemHeight(with: itemWidth)
        }
        return 20
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(for: indexPath) else { return }
        
        pushNewAdvisoryVc(with: vm)
    }
    
    func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? DepartmentViewCell
        cell?.backgroundColor = .splLineNormal
    }
    
    func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? DepartmentViewCell
        cell?.backgroundColor = .mainLight
    }
}

extension PMCDepartmentViewController: UISearchBarDelegate {
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        if !isSearchBarEditing {
            addResultSearchVc()
            isSearchBarEditing = true
        }
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if searchBar.text!.trimmingCharacters(in: .whitespaces).isEmpty {
            HUDTool.show(message: "搜索不能为空")
            return
        }
        
        resultSearchVc.view.backgroundColor = .background
        resultSearchVc.loadData(text: searchBar.text!)
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.isEmpty {
            resultSearchVc.viewModel = nil
            resultSearchVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        }
    }
}

extension PMCDepartmentViewController: DepartmentSearchResultControllerDelegate {
    func resultSearchVc(_ resultVc: DepartmentSearchResultController,
                        pushViewController vm: DepartmentViewModel.RowViewModel) {
        pushNewAdvisoryVc(with: vm)
    }
    
    func resultSearchVc(didEndEditing resultVc: DepartmentSearchResultController) {
        removeResultSearchVc()
    }
}

private extension PMCDepartmentViewController {
    func addResultSearchVc() {
        resultSearchVc.delegate = self
        resultSearchVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        addChild(resultSearchVc)
        view.addSubview(resultSearchVc.view)
        resultSearchVc.view.snp.makeConstraints { (make) in
            make.edges.equalTo(collectionView)
        }
    }
    
    func removeResultSearchVc() {
        searchBar.text = nil
        searchBar.resignFirstResponder()
        resultSearchVc.removeFromParent()
        resultSearchVc.view.removeFromSuperview()
        resultSearchVc.viewModel = nil
        isSearchBarEditing = false
    }
    
    func pushNewAdvisoryVc(with vm: DepartmentViewModel.RowViewModel) {
        let newAdvisoryVc = DoctorListViewController(departmentId: vm.departmentId)
        navigationController?.pushViewController(newAdvisoryVc, animated: true)
    }
}
